<script lang="ts" setup>
import { message } from 'ant-design-vue';
import { cloneDeep } from 'lodash-es';
import type { UnwrapRef } from 'vue';

const props = defineProps({
  mainIndicator: {
    type: String as PropType<string>,
    required: true,
  },
  date: {
    type: String as PropType<string>,
    required: true,
  },
});

const data = ref<any[]>([]);
const loading = ref<boolean>(false);

const allColumns = ref<any[]>([]);
const { auth } = useAuth();
function showRoleColumn() {
  return auth([
    'a_i_edit',
  ]);
}
const header = ref<any[]>([]);
const flag = ref<boolean>(true);
function getColumns() {
  loading.value = true;
  const oldheader = ['generalFieldA', 'generalFieldB', 'generalFieldC', 'generalFieldD', 'generalFieldE', 'generalFieldF', 'generalFieldG', 'generalFieldH', 'generalFieldI', 'generalFieldJ', 'generalFieldK', 'generalFieldL', 'generalFieldM', 'generalFieldN', 'generalFieldO'];
  const header1 = header.value[0];
  const hlength = Object.keys(header1).length;
  for (let i = 0; i < hlength - 2; i++) {
    allColumns.value.push({
      dataIndex: oldheader[i],
      align: 'center',
    });
  }
  allColumns.value.push({
    title: '操作',
    dataIndex: 'operation',
    key: 'lastColumn',
    width: '8%',
    align: 'center',
    fixed: 'right',
  });
  loading.value = false;
}
const columns: any = computed(() => {
  return allColumns.value.filter((column: any) => {
    const flag = showRoleColumn();
    if (!flag && column.title === '操作') {
      return false;
    }
    return true;
  });
});
// 获取月份呢
function convertDateStringToNumber(dateString: string) {
  const regex = /(\d{4})年(\d{2})月/;
  const matches = dateString.match(regex);
  if (matches) {
    const year = matches[1];
    const month = matches[2];
    const formattedDate = year + month;
    return Number.parseInt(formattedDate, 10);
  }
}
async function getData() {
  loading.value = true;
  const date: any = convertDateStringToNumber(props.date);
  await getKpiListByYearMonth(date).then((res: any) => {
    const alldata: any[] = res.data;
    data.value = alldata.filter(record => record.sheetName === props.mainIndicator);
    // eslint-disable-next-line no-console
    console.log(data.value);
    if (data.value.length === 0) {
      flag.value = false;
    }
  }).catch(() => {
    message.error('数据获取失败！');
    loading.value = false;
  });
  // 处理数据
  for (let i = 0; i < data.value.length; i++) {
    if (data.value[i].isField === 'true') {
      const headerdata = Object.keys(data.value[i])
        .filter(key => (key.startsWith('generalField') || key.startsWith('isField') || key.startsWith('id')) && data.value[i][key] !== '')
        .reduce((acc: any, key) => {
          acc[key] = data.value[i][key];
          return acc;
        }, {});
      header.value.push(headerdata);
    }
  }
  loading.value = false;
}

onMounted(async () => {
  await getData().then(() => {
    getColumns();
  });
});

// 编辑
const editableData: UnwrapRef<Record<string, any>> = reactive({});

function edit(id: number) {
  editableData[id] = cloneDeep(data.value.find(item => item.id === id));
}

async function save(id: number) {
  // const newData = Object.assign(data?.value?.filter((item: AAPI.Month_Item) => id === item.sequenceNumber)[0], editableData[id]);
  // const updateDate = {

  // };
  const index = data.value.findIndex(item => item.id === id);
  if (index !== -1) {
    const newData = { ...data.value[index], ...editableData[id] };
    data.value[index] = newData;
    await updateYunwangHistoryRecord(newData).then(() => {
      message.success('修改成功!');
      // eslint-disable-next-line no-console
      console.log(newData);
      delete editableData[id];
    });
  }
}

function cancel(id: number) {
  delete editableData[id];
}
</script>

<template>
  <div>
    <a-table
      :columns="columns" :data-source="data" row-key="id" :scroll="{ x: 1800, y: 300 }" class="m-table"
      :show-header="false" :loading="loading" :pagination="false"
    >
      <template #bodyCell="{ column, text, record }">
        <template v-if="column?.dataIndex === 'operation' && record.isField === 'false'">
          <div class="editable-row-operations">
            <span v-if="editableData[record.id]">
              <a-typography-link @click="save(record.id)">保存</a-typography-link>
              <a @click="cancel(record.id)">取消</a>
            </span>
            <span v-else>
              <a-space>
                <a @click="edit(record.id)">编辑</a>
              </a-space>
            </span>
          </div>
        </template>
        <template v-else-if="record.isField === 'true'">
          <div class="table-title">
            <p>{{ text }}</p>
          </div>
        </template>
        <template v-else>
          <div>
            <a-input
              v-if="editableData[record.id]" v-model:value="editableData[record.id][column.dataIndex as string]"
              style="margin: -5px 0;"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>

<style lang="scss" scoped>
.max {
  display: flex;
  flex-direction: column;
  max-width: 100%;
  max-height: 95%;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;
    height: 31px;
    margin-bottom: 10px;

    .pjTitle {
      padding-left: 15px;
      background: url("@/assets/images/title-left-bg.svg") no-repeat;
    }

    .right {
      display: flex;
      align-items: center;
    }
  }

  .content {
    height: 100%;
    overflow: auto;
  }
}

.editable-row-operations a {
  margin-right: 8px;
}
</style>
